package io.anywhere;

import com.google.common.io.Files;
import com.google.common.net.MediaType;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class SimpleStaticHttpHandler implements HttpHandler {
  public static final Map<String, String> CONTENTS_MAP = new HashMap<>();

  static {
    CONTENTS_MAP.put(".html", MediaType.HTML_UTF_8.type());

    CONTENTS_MAP.put(".js", MediaType.JAVASCRIPT_UTF_8.type());
    CONTENTS_MAP.put(".css", MediaType.CSS_UTF_8.type());

    CONTENTS_MAP.put(".png", MediaType.ANY_IMAGE_TYPE.type());
    CONTENTS_MAP.put(".jpg", MediaType.ANY_IMAGE_TYPE.type());
    CONTENTS_MAP.put(".gif", MediaType.ANY_IMAGE_TYPE.type());
    CONTENTS_MAP.put(".ico", MediaType.ANY_IMAGE_TYPE.type());
  }

  private String path;

  public SimpleStaticHttpHandler(String path) {
    this.path = path;
  }

  @Override
  public void handle(HttpExchange httpExchange) {
    String path = httpExchange.getRequestURI().getPath();

    File file = new File(this.path, path);

    try (OutputStream out = httpExchange.getResponseBody()) {
      if (file.exists() && file.canRead()) {
        int pos = file.getName().lastIndexOf(".");
        String suffix = file.getName().substring(pos);

        //设置响应头，必须在sendResponseHeaders方法之前设置！
        String mt = CONTENTS_MAP.containsKey(suffix) ? CONTENTS_MAP.get(suffix) : MediaType.HTML_UTF_8.type();
        httpExchange.getResponseHeaders().add("Content-Type:", mt);

        //设置响应码和响应体长度，必须在getResponseBody方法之前调用！
        httpExchange.sendResponseHeaders(200, file.length());

        out.write(Files.toByteArray(file));
      } else httpExchange.sendResponseHeaders(404, 0);
      out.flush();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
